/**
 * Service Worker 代理
 * 用于在PWA中处理跨域请求
 */

const CACHE_NAME = 'lcc-proxy-cache-v1';
const PROXY_ROUTES = {
  '/api/external': 'http://180.100.199.56:8006',
  '/api/192': 'http://192.168.5.114:8722',
  '/api/10': 'http://10.2.7.215:8722'
};

// 安装Service Worker
self.addEventListener('install', (event) => {
  console.log('Service Worker 代理安装中...');
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('代理缓存已创建');
        return cache;
      })
  );
});

// 激活Service Worker
self.addEventListener('activate', (event) => {
  console.log('Service Worker 代理已激活');
  event.waitUntil(
    caches.keys().then((cacheNames) => {
      return Promise.all(
        cacheNames.map((cacheName) => {
          if (cacheName !== CACHE_NAME) {
            console.log('删除旧缓存:', cacheName);
            return caches.delete(cacheName);
          }
        })
      );
    })
  );
});

// 拦截请求
self.addEventListener('fetch', (event) => {
  const url = new URL(event.request.url);
  
  // 检查是否是代理请求
  for (const [proxyPath, targetUrl] of Object.entries(PROXY_ROUTES)) {
    if (url.pathname.startsWith(proxyPath)) {
      event.respondWith(handleProxyRequest(event.request, proxyPath, targetUrl));
      return;
    }
  }
  
  // 检查是否是直接的跨域请求
  if (isCrossOriginRequest(url)) {
    event.respondWith(handleCrossOriginRequest(event.request));
    return;
  }
});

/**
 * 处理代理请求
 */
async function handleProxyRequest(request, proxyPath, targetUrl) {
  const url = new URL(request.url);
  const targetPath = url.pathname.replace(proxyPath, '');
  const fullTargetUrl = `${targetUrl}${targetPath}${url.search}`;
  
  console.log(`代理请求: ${request.url} -> ${fullTargetUrl}`);
  
  try {
    // 创建新的请求对象
    const proxyRequest = new Request(fullTargetUrl, {
      method: request.method,
      headers: createProxyHeaders(request.headers),
      body: request.method !== 'GET' && request.method !== 'HEAD' ? await request.clone().arrayBuffer() : undefined,
      mode: 'cors',
      credentials: 'omit'
    });
    
    const response = await fetch(proxyRequest);
    
    // 创建响应对象，添加CORS头
    const proxyResponse = new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: createCORSHeaders(response.headers)
    });
    
    console.log(`代理响应: ${response.status} ${fullTargetUrl}`);
    return proxyResponse;
    
  } catch (error) {
    console.error('代理请求失败:', error);
    
    // 返回错误响应
    return new Response(JSON.stringify({
      error: '代理请求失败',
      message: error.message,
      url: fullTargetUrl
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization'
      }
    });
  }
}

/**
 * 处理跨域请求
 */
async function handleCrossOriginRequest(request) {
  const url = new URL(request.url);
  
  console.log(`处理跨域请求: ${request.url}`);
  
  try {
    // 尝试直接请求
    const response = await fetch(request);
    return response;
  } catch (error) {
    console.error('跨域请求失败:', error);
    
    // 尝试从缓存获取
    const cachedResponse = await caches.match(request);
    if (cachedResponse) {
      console.log('从缓存返回响应');
      return cachedResponse;
    }
    
    // 返回错误响应
    return new Response(JSON.stringify({
      error: '跨域请求失败',
      message: error.message,
      url: request.url
    }), {
      status: 500,
      headers: {
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization'
      }
    });
  }
}

/**
 * 检查是否是跨域请求
 */
function isCrossOriginRequest(url) {
  const currentOrigin = self.location.origin;
  return url.origin !== currentOrigin;
}

/**
 * 创建代理请求头
 */
function createProxyHeaders(originalHeaders) {
  const headers = new Headers();
  
  // 复制原始请求头，但移除可能导致问题的头
  for (const [key, value] of originalHeaders.entries()) {
    if (!['host', 'origin', 'referer'].includes(key.toLowerCase())) {
      headers.set(key, value);
    }
  }
  
  // 添加代理标识
  headers.set('X-Proxy-By', 'LCC-Service-Worker');
  headers.set('X-Original-Origin', self.location.origin);
  
  return headers;
}

/**
 * 创建CORS响应头
 */
function createCORSHeaders(originalHeaders) {
  const headers = new Headers(originalHeaders);
  
  // 添加CORS头
  headers.set('Access-Control-Allow-Origin', '*');
  headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
  headers.set('Access-Control-Max-Age', '86400');
  
  return headers;
}

/**
 * 处理OPTIONS预检请求
 */
self.addEventListener('fetch', (event) => {
  if (event.request.method === 'OPTIONS') {
    event.respondWith(handleOptionsRequest(event.request));
  }
});

function handleOptionsRequest(request) {
  return new Response(null, {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
      'Access-Control-Max-Age': '86400'
    }
  });
}

console.log('Service Worker 代理已加载');
